package com.emm.yixun.website.controller.system;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.emm.yixun.common.model.dto.*;
import com.emm.yixun.common.model.enums.*;
import com.emm.yixun.customer.service.SubscribeServiceFacade;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.emm.yixun.anotations.MerchantResourcesConfig;
import com.emm.yixun.common.enums.DictionaryTypeEnums;
import com.emm.yixun.common.model.Dictionary;
import com.emm.yixun.common.model.MsgSetting;
import com.emm.yixun.common.model.NeedReceiveRefundInfo;
import com.emm.yixun.common.model.Project;
import com.emm.yixun.common.model.Resources;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.page.PageUtil;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.customer.service.CustomerServiceFacade;
import com.emm.yixun.estate.service.ProjectServiceFacade;
import com.emm.yixun.marketing.service.NeedReceiveRefundServiceFacade;
import com.emm.yixun.system.service.DictionaryServiceFacade;
import com.emm.yixun.system.service.MerchantServiceFacade;
import com.emm.yixun.system.service.MsgSettingServiceFacade;
import com.emm.yixun.system.service.MsgTempServiceFacade;
import com.emm.yixun.system.service.NoticeServiceFacade;
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.common.utils.base.Const;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.common.utils.tree.MenuTreeUtil;
import com.emm.yixun.website.constant.ConstantConfig;
import com.emm.yixun.website.controller.base.BaseController;
import com.emm.yixun.website.service.system.resources.ResourcesService;
import com.emm.yixun.website.utils.ExcelUtil;

import net.sf.json.JSONArray;

@Controller
@RequestMapping("/backstage/")
public class BackstageController extends BaseController<Object> {

	@Autowired
	public ResourcesService menuService;
	@Resource
	private ProjectServiceFacade projectServiceFacade;
	@Resource
	private DictionaryServiceFacade dictionaryServiceFacade;
	@Resource
	private NoticeServiceFacade noticeServiceFacade;
	@Resource
	private MsgTempServiceFacade msgTempServiceFacade;
	@Resource
	private MsgSettingServiceFacade msgSettingServiceFacade;
	@Autowired
	private MerchantServiceFacade merchantServiceFacade;
	@Autowired
	private CustomerServiceFacade customerServiceFacade;
	@Autowired
	private NeedReceiveRefundServiceFacade needReceiveRefundServiceFacade;
	@Autowired
	private ConstantConfig constantConfig;
	@Autowired
	private SubscribeServiceFacade subscribeServiceFacade;

	/**
	 * 访问系统首页
	 */
	@RequestMapping("index")
	public String index(Model model) {
		// shiro获取用户信息
		User user = ShiroUtil.getCurrentUser();
		model.addAttribute("currentAccount", user);
		model.addAttribute("merchantAccount", merchantServiceFacade.findById(user.getMerchantId()).getEntity());
		model.addAttribute("helpDocument", constantConfig.getHelpDocument());
		return "/system/index";
	}

	@RequestMapping(value = "menu/getMenu", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes getMenu() {
		AjaxRes ar = getAjaxRes();
		try {
			List<com.emm.yixun.common.model.Resources> menus = getRoleMenuResources();
			if (menus != null) {
				// 将对象处理成树
				String html = MenuTreeUtil.buildTreeHtml(menus);
				ar.setSucceed(html);
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
			ar.setFailMsg("获取菜单失败");
		}
		return ar;
	}

	@RequestMapping("adv")
	@MerchantResourcesConfig(resourcesCode="menu_0001")
	public ModelAndView advUI(Model model, HttpServletRequest request, HttpServletResponse response) {
		if (doSecurityIntercept(Const.RESOURCES_TYPE_MENU)) {
			User user = ShiroUtil.getCurrentUser();
			ModelAndView mv = new ModelAndView("/system/adv/adv");
			// 查询菜单按钮权限
			List<Resources> resourcesList = getPermitBtn(Const.RESOURCES_TYPE_FUNCTION);
			mv.addObject("btnJson", JSONArray.fromObject(resourcesList));
			mv.addObject("permitBtn", resourcesList);
			ProjectDto projectDto = new ProjectDto();
			projectDto.setMerchantId(user.getMerchantId());
			projectDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			projectDto.setPermissionUserId(user.getId());
			ResponseList<Project> projectList = projectServiceFacade.findByDto(projectDto);
			if (projectList.isSuccess()) {
				mv.addObject("projectList", projectList.getEntity());
			}
			DictionaryDto dicDto = new DictionaryDto();
			dicDto.setDelFlag("0");
			dicDto.setDictionaryType(DictionaryTypeEnums.NOTICE_TYPE.getNo());
			ResponseList<Dictionary> dicListRes = dictionaryServiceFacade.findByDto(dicDto);
			if (dicListRes.isSuccess()) {
				mv.addObject("dictionaryList", dicListRes.getEntity());
			}
			/*
			 * 提醒消息
			 * 逾期未签约  overdueSignedListCount
			 * 逾期未付款 overduePaymentListCount
			 * 待处理客户 RE03
			 * 客户维护 RE04
			 * 审核结果 RE05
			 * 审核申请 RE06
			 * 客户关怀 RE07
			 * 员工关怀 RE07
			 */
			SubscribeDto subscribeDto = new SubscribeDto();
			subscribeDto.setMerchantId(user.getMerchantId());
			subscribeDto.setPermissionUserId(user.getId());
			subscribeDto.setResourcesCode("menu_0100_0001");
			Response<Integer> overdueSignedListCount = subscribeServiceFacade.getOverdueSignedListCount(subscribeDto);
			mv.addObject("overdueSignedListCount", overdueSignedListCount.getEntity());

			NeedReceiveRefundDto dto = new NeedReceiveRefundDto();
			dto.setMerchantId(user.getMerchantId());
			dto.setPermissionUserId(user.getId());
			dto.setResourcesCode("menu_0100_0002");
			Response<Integer> overduePaymentListCount = needReceiveRefundServiceFacade.getOverduePaymentListCount(dto);
			mv.addObject("overduePaymentListCount", overduePaymentListCount.getEntity());

			//mv.addObject("RE01", findTxCount(user,"逾期未签约"));
			//mv.addObject("RE02", findTxCount(user,"逾期未付款"));
			//mv.addObject("RE03", findTxCount(user,"待处理客户"));
			//mv.addObject("RE04", findTxCount(user,"客户维护"));
			//mv.addObject("RE05", findTxCount(user,"审核结果"));
			//mv.addObject("RE06", findTxCount(user,"审核申请"));
			//mv.addObject("RE07", findTxCount(user,"客户关怀"));
			//mv.addObject("RE08", findTxCount(user,"员工关怀"));
			
			// 模板消息
			MsgSettingDto settingDto = new MsgSettingDto();
			settingDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			settingDto.setMerchantId(user.getMerchantId());
			ResponseList<MsgSetting> settingRes = msgSettingServiceFacade.findByDto(settingDto);
			if (settingRes.isSuccess()) {
				List<MsgSetting> settingList = settingRes.getEntity();
				if (settingList != null) {
					for (MsgSetting setting : settingList) {
						if (TempTypeEnum.RE04.getNo().equals(setting.getTempType())) {
							// 客户维护模板
							mv.addObject("RE04Temp", setting);
						} else if (TempTypeEnum.RE07.getNo().equals(setting.getTempType())) {
							// 客户关怀模板
							mv.addObject("RE07Temp", setting);
						} else if (TempTypeEnum.RE08.getNo().equals(setting.getTempType())) {
							// 员工关怀模板
							mv.addObject("RE08Temp", setting);
						}
					}
				}
			}
			return mv;
		} else {
			return new ModelAndView(Const.NO_AUTHORIZED_URL);
		}

	}

	@RequestMapping("advLC")
	public ModelAndView advUILC(Model model) {
		if (doSecurityIntercept(Const.RESOURCES_TYPE_MENU,"/backstage/adv")) {
			User user = ShiroUtil.getCurrentUser();
			ModelAndView mv = new ModelAndView("/system/adv/adv");
			// 查询菜单按钮权限
			List<Resources> resourcesList = getPermitBtn(Const.RESOURCES_TYPE_FUNCTION);
			mv.addObject("btnJson", JSONArray.fromObject(resourcesList));
			mv.addObject("permitBtn", resourcesList);
			ProjectDto projectDto = new ProjectDto();
			projectDto.setMerchantId(user.getMerchantId());
			projectDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			projectDto.setPermissionUserId(user.getId());
			ResponseList<Project> projectList = projectServiceFacade.findByDto(projectDto);
			if (projectList.isSuccess()) {
				mv.addObject("projectList", projectList.getEntity());
			}
			DictionaryDto dicDto = new DictionaryDto();
			dicDto.setDelFlag("0");
			dicDto.setDictionaryType(DictionaryTypeEnums.NOTICE_TYPE.getNo());
			ResponseList<Dictionary> dicListRes = dictionaryServiceFacade.findByDto(dicDto);
			if (dicListRes.isSuccess()) {
				mv.addObject("dictionaryList", dicListRes.getEntity());
			}
			/*
			 * 提醒消息
			 * 逾期未签约  overdueSignedListCount
			 * 逾期未付款 overduePaymentListCount
			 * 待处理客户 RE03
			 * 客户维护 RE04
			 * 审核结果 RE05
			 * 审核申请 RE06
			 * 客户关怀 RE07
			 * 员工关怀 RE07
			 */
			SubscribeDto subscribeDto = new SubscribeDto();
			subscribeDto.setMerchantId(user.getMerchantId());
			subscribeDto.setPermissionUserId(user.getId());
			subscribeDto.setResourcesCode("menu_0100_0001");
			Response<Integer> overdueSignedListCount = subscribeServiceFacade.getOverdueSignedListCount(subscribeDto);
			mv.addObject("overdueSignedListCount", overdueSignedListCount.getEntity());

			NeedReceiveRefundDto dto = new NeedReceiveRefundDto();
			dto.setMerchantId(user.getMerchantId());
			dto.setPermissionUserId(user.getId());
			dto.setResourcesCode("menu_0100_0002");
			Response<Integer> overduePaymentListCount = needReceiveRefundServiceFacade.getOverduePaymentListCount(dto);
			mv.addObject("overduePaymentListCount", overduePaymentListCount.getEntity());
			//mv.addObject("RE01", findTxCount(user,"逾期未签约"));
			//mv.addObject("RE02", findTxCount(user,"逾期未付款"));
			//mv.addObject("RE03", findCustomerNotice(user,"待处理客户"));
			//mv.addObject("RE04", findTxCount(user,"客户维护"));
			//mv.addObject("RE05", findTxCount(user,"审核结果"));
			//mv.addObject("RE06", findTxCount(user,"审核申请"));
			//mv.addObject("RE07", findTxCount(user,"客户关怀"));
			//mv.addObject("RE08", findTxCount(user,"员工关怀"));

			// 模板消息
			MsgSettingDto settingDto = new MsgSettingDto();
			settingDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			settingDto.setMerchantId(user.getMerchantId());
			ResponseList<MsgSetting> settingRes = msgSettingServiceFacade.findByDto(settingDto);
			if (settingRes.isSuccess()) {
				List<MsgSetting> settingList = settingRes.getEntity();
				if (settingList != null) {
					for (MsgSetting setting : settingList) {
						if (TempTypeEnum.RE04.getNo().equals(setting.getTempType())) {
							// 客户维护模板
							mv.addObject("RE04Temp", setting);
						} else if (TempTypeEnum.RE07.getNo().equals(setting.getTempType())) {
							// 客户关怀模板
							mv.addObject("RE07Temp", setting);
						} 
					}
				}
			}
			return mv;
		} else {
			return new ModelAndView(Const.NO_AUTHORIZED_URL);
		}

	}
	
	private List<Long> findTXByRemark(String remark){
		List<Long> ids=new ArrayList<Long>();
		DictionaryDto dicDto = new DictionaryDto();
		dicDto.setRemark(remark);
		ResponseList<Dictionary> dicListRes = dictionaryServiceFacade.findByDto(dicDto);
		if(dicListRes.isSuccess() && null!=dicListRes.getEntity()){
			for(Dictionary  dictionary : dicListRes.getEntity()){
				ids.add(dictionary.getId());
			}
		}else{
			//如果类型不存在，则默认-999  即不能查到该消息类型
			ids.add(Long.valueOf(-999));
		}
		return ids;
	}


	//
	private int findCustomerNotice(User user,String remark){
		ReceiverNoticeDto receiverNoticeDto=new ReceiverNoticeDto();
		receiverNoticeDto.setMerchantId(user.getMerchantId());
		receiverNoticeDto.setNoticeType(NoticeTypeEnum.REMIND.getNo());
		receiverNoticeDto.setReceiveStatus(ReceiveStatusEnum.UNRECEIVED.getNo());
		receiverNoticeDto.setReceiverUserId(user.getId());
		receiverNoticeDto.setDictionaryIds(findTXByRemark(remark));
		Response<Integer> countResponse=noticeServiceFacade.receiverNoticeCount(receiverNoticeDto);

		//查询完善客户信息
		CustomerComponentDto dto = new CustomerComponentDto();
		//	dto.setUserCode(user.getUserCode());
		dto = setCustValue(dto);
		int countCustomer = customerServiceFacade.findIntentionIntactCount(dto);

		if(countResponse.isSuccess()){
			return Integer.parseInt(countResponse.getEntity().toString()) + countCustomer ;
		}

		return countCustomer;
	}
	private CustomerComponentDto setCustValue(CustomerComponentDto dto) {
		if (dto.getFtContactTimeAfter() != null && !dto.getFtContactTimeAfter().equals("")) {
			dto.setFtContactTimeAfter(dto.getFtContactTimeAfter() + " 23:59:59");
		}
		//最新跟进时间
		if (StringUtils.isNotBlank(dto.getLastFollowTimeBefore())) {
			dto.setLastFollowTimeBefore(dto.getLastFollowTimeBefore() + " 00:00:00");
		}
		if (StringUtils.isNotBlank(dto.getLastFollowTimeAfter())) {
			dto.setLastFollowTimeAfter(dto.getLastFollowTimeAfter() + " 23:59:59");
		}
		//录入时间（即为业务创建时间）
		if (StringUtils.isNotBlank(dto.getCreateTimeBefore())) {
			dto.setCreateTimeBefore(dto.getCreateTimeBefore() + " 00:00:00");
		}

		if (StringUtils.isNotBlank(dto.getCreateTimeAfter())) {
			dto.setCreateTimeAfter(dto.getCreateTimeAfter() + " 23:59:59");
		}
		if (dto.getUserCode() != null && dto.getUserCode().equals("-1")) {
			dto.setUserCode(null);
		}

		// 数据权限
		User user = ShiroUtil.getCurrentUser();
		//dto.setPermissionUserId(user.getId());
		dto.setUserCode(user.getUserCode());
		dto.setMerchantId(user.getMerchantId());
		dto.setOrders(" t.create_time desc ");
		return dto;
	}
	private int findTxCount(User user,String remark){
		ReceiverNoticeDto receiverNoticeDto=new ReceiverNoticeDto();
		receiverNoticeDto.setMerchantId(user.getMerchantId());
		receiverNoticeDto.setNoticeType(NoticeTypeEnum.REMIND.getNo());
		receiverNoticeDto.setReceiveStatus(ReceiveStatusEnum.UNRECEIVED.getNo());
		receiverNoticeDto.setReceiverUserId(user.getId());
		receiverNoticeDto.setDictionaryIds(findTXByRemark(remark));
		Response<Integer> countResponse=noticeServiceFacade.receiverNoticeCount(receiverNoticeDto);
		if(countResponse.isSuccess()){
			return countResponse.getEntity();
		}
		return 0;
	}

	@RequestMapping("404")
	public String errorlistUI(Model model) {
		return "/system/error/404";
	}

	/**
	 * 没权限页面
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("noAuthorized")
	public String noAuthorizedUI(Model model) {
		return Const.NO_AUTHORIZED_URL;
	}
	
	/**
	 * 签约回款提醒条数,默认查询近10天的
	 * @param request
	 * @return
	 */
	@RequestMapping("selectNonpaymentNum")
	@ResponseBody
	public AjaxRes selectNonpaymentNum(HttpServletRequest request) {
		AjaxRes ar = getAjaxRes();
		try {
			//获取当前用户信息
			User user = ShiroUtil.getCurrentUser();
			
			NeedReceiveRefundDto dto = new NeedReceiveRefundDto();
			dto.setMerchantId(user.getMerchantId());
			dto.setPermissionUserId(user.getId());
			dto.setResourcesCode("menu_0003_0001");
			Response<Integer> response = needReceiveRefundServiceFacade.selectNonpaymentNum(dto, 10);
			if (response.isSuccess()) {
				ar.setObj(response.getEntity());
				ar.setRes(Const.SUCCEED);
			} 
		} catch (Exception e) {
			logger.error("查询签约回款提醒数失败", e);
		}
		return ar;
	}
	
	@RequestMapping("toNonpaymentList")
	public String toNonpaymentList(Model model) {
		return "/system/adv/nonpaymentList";
	}


	/**
	 * 签约回款提醒列表,默认查询近10天的
	 * @param request
	 * @return
	 */
	@RequestMapping("selectNonpaymentPage")
	@ResponseBody
	public AjaxRes selectNonpaymentPage(HttpServletRequest request, int pageNum, int pageSize) {
		AjaxRes ar = getAjaxRes();
		try {
			//获取项目名称
			Long projectId = null;
			if(StringUtils.isNotBlank(request.getParameter("projectId"))) {
				projectId = Long.parseLong(request.getParameter("projectId"));
			}
			//获取经纪人
			String userCode = request.getParameter("userCode");
			if(StringUtils.isBlank(userCode) || userCode.equals("null")) {
				userCode = null;
			}
			//获取到期天数
			int day = 10;
			if(StringUtils.isNotBlank(request.getParameter("day"))) {
				day = Integer.parseInt(request.getParameter("day"));
			}
			//获取当前用户信息
			User user = ShiroUtil.getCurrentUser();
			
			NeedReceiveRefundDto dto = new NeedReceiveRefundDto();
			dto.setMerchantId(user.getMerchantId());
			dto.setUserCode(userCode);
			dto.setPermissionUserId(user.getId());
			dto.setResourcesCode("menu_0003_0001");
			Page<NeedReceiveRefundInfo> response = needReceiveRefundServiceFacade.selectNonpaymentPage(dto, projectId, day, 
					PageUtil.begin(pageNum, pageSize),pageSize);
			if(response.getSuccess()){
                if(null==response.getRows()){
                    response.setRows(new ArrayList<NeedReceiveRefundInfo>());
                }
            	response.setPageNumber(pageNum);
            	ar.setSucceed(response);
            }else{
            	ar.setFailMsg(Const.DATA_FAIL);
            }
		} catch (Exception e) {
			logger.error("查询签约回款提醒数失败", e);
		}
		return ar;
	}
	
	/**
	 * 导出签约回款提醒列表,默认查询近10天的
	 * @param request
	 * @return
	 */
	@RequestMapping("exportNonpaymentList")
	public String exportNonpaymentList(HttpServletRequest request, HttpServletResponse response, Model model) {
		try {
			//获取项目名称
			Long projectId = null;
			if(StringUtils.isNotBlank(request.getParameter("projectId"))) {
				projectId = Long.parseLong(request.getParameter("projectId"));
			}
			//获取经纪人
			String userCode = request.getParameter("userCode");
			if(StringUtils.isBlank(userCode) || userCode.equals("null")) {
				userCode = null;
			}
			//获取到期天数
			int day = 10;
			if(StringUtils.isNotBlank(request.getParameter("day"))) {
				day = Integer.parseInt(request.getParameter("day"));
			}
			//获取当前用户信息
			User user = ShiroUtil.getCurrentUser();
			
			NeedReceiveRefundDto dto = new NeedReceiveRefundDto();
			dto.setMerchantId(user.getMerchantId());
			dto.setUserCode(userCode);
			dto.setPermissionUserId(user.getId());
			dto.setResourcesCode("menu_0003_0001");
			ResponseList<NeedReceiveRefundInfo> resList = needReceiveRefundServiceFacade
					.selectNonpaymentList(dto, projectId, day);
			if(!resList.isSuccess() || resList.getEntity() == null) {
				logger.error("导出签约回款提醒列表失败", resList.getResultMessage());
				return "/system/adv/nonpaymentList";
			}
			List<NeedReceiveRefundInfo> infoList = resList.getEntity();
			
			//设置excel sheet
			String[] name = {"签约回款提醒"};
			//设置excel 列表表头
			List<String[]> headerList = new ArrayList<String[]>(); 
			String[] header = {
				"客户姓名", "联系电话", "客户性别", "房号", "签约面积", "签约单价", "签约金额", "房款类型", "应收金额",
				"应收日期", "到期天数", "已收金额", "未收金额"
			};
			headerList.add(header);
			//组装数据
			List<List<Map<String, String>>> list = new ArrayList<List<Map<String, String>>>(); //数据集合
			List<Map<String, String>> listMap = exportNonpaymentList(infoList, header);
			list.add(listMap);
			ExcelUtil.exportExcel(list, headerList, name, response);
		} catch (Exception e) {
			logger.error("导出签约回款提醒列表失败", e);
		}
		return null;
	}
	
	/**
	 * 组装导出签约回款提醒数据
	 */
	private List<Map<String, String>> exportNonpaymentList(List<NeedReceiveRefundInfo> list, String[] head) {
		List<Map<String, String>> listMap = new ArrayList<Map<String,String>>();
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			for (int i=0;i<list.size();i++) {
				NeedReceiveRefundInfo info = list.get(i);
				Map<String, String> map = new HashMap<String, String>();
				map.put(head[0]+"_"+i, info.getCustomer_name()); //客户姓名
				map.put(head[1]+"_"+i, info.getCustomerPhone()); //联系电话
				map.put(head[2]+"_"+i, info.getCustomerSex()); //客户性别
				map.put(head[3]+"_"+i, info.getCombined_name()); //房号
				map.put(head[4]+"_"+i, info.getCalculatArea()); //签约面积
				map.put(head[5]+"_"+i, info.getPrice().toString()); //签约单价
				map.put(head[6]+"_"+i, info.getTotalPrice().toString()); //签约金额
				map.put(head[7]+"_"+i, info.getRelationType()); //房款类型
				map.put(head[8]+"_"+i, info.getTotalReceivablesAmount().toString()); //应收金额
				map.put(head[9]+"_"+i, sdf.format(info.getReceivablesDate())); //应收日期
				map.put(head[10]+"_"+i, String.valueOf(info.getReceivablesDay())); //到期天数
				map.put(head[11]+"_"+i, info.getReceivedAmount().toString()); //已收金额
				map.put(head[12]+"_"+i, info.getUncollectedAmount().toString()); //未收金额
				listMap.add(map);
			}
		} catch (Exception e) {
			logger.error("组装导出签约回款提醒数据错误：{}",e);
		}
		return listMap;
	}


	/**
	 * 逾期未签约提醒
	 * @param model
	 * @return
	 */
	@RequestMapping("toOverdueSignedList")
	public String toOverdueSignedList(Model model) {
		return "/system/adv/overduesignedlist";
	}


	/**
	 * 逾期未签约列表
	 * @param request
	 * @return
	 */
	@RequestMapping("selectOverdueSignedPage")
	@ResponseBody
	public AjaxRes selectOverdueSignedPage(HttpServletRequest request, int pageNum, int pageSize) {
		AjaxRes ar = getAjaxRes();
		try {
			//获取项目名称
			Long projectId = null;
			if(StringUtils.isNotBlank(request.getParameter("projectId"))) {
				projectId = Long.parseLong(request.getParameter("projectId"));
			}
			//获取经纪人
			String userCode = request.getParameter("userCode");
			if(StringUtils.isBlank(userCode) || userCode.equals("null")) {
				userCode = null;
			}
			//获取当前用户信息
			User user = ShiroUtil.getCurrentUser();
			SubscribeDto subscribeDto = new SubscribeDto();
			subscribeDto.setMerchantId(user.getMerchantId());
			subscribeDto.setPermissionUserId(user.getId());
			subscribeDto.setProjectId(projectId);
			subscribeDto.setUserCode(userCode);
			subscribeDto.setResourcesCode("menu_0100_0001");
			Page<SubscribeDto> response = subscribeServiceFacade.getOverdueSignedPageModel(subscribeDto, PageUtil.begin(pageNum, pageSize),pageSize);

			if(response.getSuccess()){
				if(null==response.getRows()){
					response.setRows(new ArrayList<SubscribeDto>());
				}
				response.setPageNumber(pageNum);
				ar.setSucceed(response);
			}else{
				ar.setFailMsg(Const.DATA_FAIL);
			}
		} catch (Exception ex) {
			logger.error("查询逾期未签约记录失败", ex);
		}
		return ar;
	}

	/**
	 * 导出逾期未签约列表
	 * @param request
	 * @return
	 */
	@RequestMapping("exportOverdueSignedList")
	public String exportOverdueSignedList(HttpServletRequest request, HttpServletResponse response, Model model) {
		try {
			//获取项目名称
			Long projectId = null;
			if(StringUtils.isNotBlank(request.getParameter("projectId"))) {
				projectId = Long.parseLong(request.getParameter("projectId"));
			}
			//获取经纪人
			String userCode = request.getParameter("userCode");
			if(StringUtils.isBlank(userCode) || userCode.equals("null")) {
				userCode = null;
			}
			//获取当前用户信息
			//获取当前用户信息
			User user = ShiroUtil.getCurrentUser();
			SubscribeDto subscribeDto = new SubscribeDto();
			subscribeDto.setMerchantId(user.getMerchantId());
			subscribeDto.setPermissionUserId(user.getId());
			subscribeDto.setProjectId(projectId);
			subscribeDto.setUserCode(userCode);
			subscribeDto.setResourcesCode("menu_0100_0001");
			//导出: 写死查1W条
			Page<SubscribeDto> resultPage = subscribeServiceFacade.getOverdueSignedPageModel(subscribeDto, 0, 10000);
			if(!resultPage.getSuccess() || null == resultPage.getRows()) {
				logger.error("导出签约回款提醒列表失败", resultPage.getErrorMsg());
				return "/system/adv/overduesignedlist";
			}

			List<SubscribeDto> subDtoList = resultPage.getRows();

			//设置excel sheet
			String[] name = {"逾期未签约提醒"};
			//设置excel 列表表头
			List<String[]> headerList = new ArrayList<String[]>();
			String[] header = {
					"客户姓名", "联系电话", "客户性别", "房号", "计价面积", "认购金额", "认购单价", "应收定金", "已收金额",
					"转签约日期", "延期天数"
			};
			headerList.add(header);
			//组装数据
			List<List<Map<String, String>>> list = new ArrayList<List<Map<String, String>>>(); //数据集合
			List<Map<String, String>> listMap = buildOverdueSignedList(subDtoList, header);
			list.add(listMap);
			ExcelUtil.exportExcel(list, headerList, name, response);
		} catch (Exception e) {
			logger.error("导出逾期未签约列表失败", e);
		}
		return null;
	}

	/**
	 * 组装导出逾期未签约数据
	 */
	private List<Map<String, String>> buildOverdueSignedList(List<SubscribeDto> list, String[] head) {
		List<Map<String, String>> listMap = new ArrayList<Map<String,String>>();
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			for (int i=0;i<list.size();i++) {
				SubscribeDto subDto = list.get(i);
				Map<String, String> map = new HashMap<String, String>();
				map.put(head[0]+"_"+i, subDto.getCustomerName()); //客户姓名
				map.put(head[1]+"_"+i, subDto.getCustomerPhone()); //联系电话
				map.put(head[2]+"_"+i, (CustomerSexEnum.MALE.getNo().equals(subDto.getCustomerSex())?"男": "女")); //客户性别
				map.put(head[3]+"_"+i, subDto.getCombinedName()); //房号
				map.put(head[4]+"_"+i, String.valueOf(subDto.getCalculateArea())); //计价面积
				map.put(head[5]+"_"+i, String.valueOf(subDto.getSubscribeAmount())); //签约单价
				map.put(head[6]+"_"+i, String.valueOf(subDto.getSubscribePrice())); //签约金额
				map.put(head[7]+"_"+i, String.valueOf(subDto.getDepositReceivable())); //房款类型
				map.put(head[8]+"_"+i, subDto.getHaveReceived()==null?"0":subDto.getHaveReceived()); //应收金额
				map.put(head[9]+"_"+i, sdf.format(subDto.getConversionSignDate())); //转签约日期
				map.put(head[10]+"_"+i, String.valueOf(subDto.getOverdueDay())); //延期天数
				listMap.add(map);
			}
		} catch (Exception e) {
			logger.error("组装导出签约回款提醒数据错误：{}",e);
		}
		return listMap;
	}

	/**
	 * 逾期未付款提醒
	 * @param model
	 * @return
	 */
	@RequestMapping("toOverduePaymentList")
	public String toOverduePaymentList(Model model) {
		return "/system/adv/overduepaymentlist";
	}

	/**
	 * 逾期未付款提醒列表
	 * @param request
	 * @return
	 */
	@RequestMapping("selectOverduePaymentPage")
	@ResponseBody
	public AjaxRes selectOverduePaymentPage(HttpServletRequest request, int pageNum, int pageSize) {
		AjaxRes ar = getAjaxRes();
		try {
			//获取项目名称
			Long projectId = null;
			if(StringUtils.isNotBlank(request.getParameter("projectId"))) {
				projectId = Long.parseLong(request.getParameter("projectId"));
			}
			//获取经纪人
			String userCode = request.getParameter("userCode");
			if(StringUtils.isBlank(userCode) || userCode.equals("null")) {
				userCode = null;
			}
			//获取当前用户信息
			User user = ShiroUtil.getCurrentUser();

			NeedReceiveRefundDto dto = new NeedReceiveRefundDto();
			dto.setMerchantId(user.getMerchantId());
			dto.setPermissionUserId(user.getId());
			dto.setProjectId(projectId);
			dto.setUserCode(userCode);
			dto.setPermissionUserId(user.getId());
			dto.setResourcesCode("menu_0100_0002");
			Page<NeedReceiveRefundInfo> response = needReceiveRefundServiceFacade.getOverduePaymentPageModel(dto, PageUtil.begin(pageNum, pageSize),pageSize);
			if(response.getSuccess()){
				if(null==response.getRows()){
					response.setRows(new ArrayList<NeedReceiveRefundInfo>());
				}
				response.setPageNumber(pageNum);
				ar.setSucceed(response);
			}else{
				ar.setFailMsg(Const.DATA_FAIL);
			}
		} catch (Exception e) {
			logger.error("查询逾期未付款失败", e);
		}
		return ar;
	}

	/**
	 * 导出逾期未付款列表
	 * @param request
	 * @return
	 */
	@RequestMapping("exportOverduePaymentList")
	public String exportOverduePaymentList(HttpServletRequest request, HttpServletResponse response, Model model) {
		try {
			//获取项目名称
			Long projectId = null;
			if(StringUtils.isNotBlank(request.getParameter("projectId"))) {
				projectId = Long.parseLong(request.getParameter("projectId"));
			}
			//获取经纪人
			String userCode = request.getParameter("userCode");
			if(StringUtils.isBlank(userCode) || userCode.equals("null")) {
				userCode = null;
			}
			//获取当前用户信息
			User user = ShiroUtil.getCurrentUser();

			NeedReceiveRefundDto dto = new NeedReceiveRefundDto();
			dto.setMerchantId(user.getMerchantId());
			dto.setPermissionUserId(user.getId());
			dto.setProjectId(projectId);
			dto.setUserCode(userCode);
			dto.setPermissionUserId(user.getId());
			dto.setResourcesCode("menu_0100_0002");
			Page<NeedReceiveRefundInfo> resList = needReceiveRefundServiceFacade
					.getOverduePaymentPageModel(dto, 0, 10000);
			if(!resList.getSuccess() || resList.getRows() == null) {
				logger.error("导出逾期未付款列表失败", resList.getErrorMsg());
				return "/system/adv/overduepaymentlist";
			}
			List<NeedReceiveRefundInfo> infoList = resList.getRows();

			//设置excel sheet
			String[] name = {"逾期未付款提醒"};
			//设置excel 列表表头
			List<String[]> headerList = new ArrayList<String[]>();
			String[] header = {
					"客户姓名", "联系电话", "客户性别", "房号", "签约面积", "签约单价", "签约金额", "房款类型", "应收金额",
					"已收金额", "未收金额", "应收日期", "逾期天数"
			};
			headerList.add(header);
			//组装数据
			List<List<Map<String, String>>> list = new ArrayList<List<Map<String, String>>>(); //数据集合
			List<Map<String, String>> listMap = buildOverduePaymentList(infoList, header);
			list.add(listMap);
			ExcelUtil.exportExcel(list, headerList, name, response);
		} catch (Exception e) {
			logger.error("导出逾期未付款列表失败", e);
		}
		return null;
	}

	/**
	 * 组装导出逾期未付款数据
	 */
	private List<Map<String, String>> buildOverduePaymentList(List<NeedReceiveRefundInfo> list, String[] head) {
		List<Map<String, String>> listMap = new ArrayList<Map<String,String>>();
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			for (int i=0;i<list.size();i++) {
				NeedReceiveRefundInfo info = list.get(i);
				Map<String, String> map = new HashMap<String, String>();
				map.put(head[0]+"_"+i, info.getCustomer_name()); //客户姓名
				map.put(head[1]+"_"+i, info.getCustomerPhone()); //联系电话
				map.put(head[2]+"_"+i, (CustomerSexEnum.MALE.getNo().equals(info.getCustomerSex())?"男": "女")); //客户性别
				map.put(head[3]+"_"+i, info.getCombined_name()); //房号
				map.put(head[4]+"_"+i, info.getCalculatArea()); //签约面积
				map.put(head[5]+"_"+i, String.valueOf(info.getPrice())); //签约单价
				map.put(head[6]+"_"+i, String.valueOf(info.getTotalPrice().toString())); //签约金额
				map.put(head[7]+"_"+i, info.getReceivablesFunds()); //房款类型
				map.put(head[8]+"_"+i, String.valueOf(info.getTotalReceivablesAmount().toString())); //应收金额
				map.put(head[9]+"_"+i, info.getReceivedAmount().toString()); //已收金额
				map.put(head[10]+"_"+i, info.getUncollectedAmount().toString()); //未收金额
				map.put(head[11]+"_"+i, sdf.format(info.getReceivablesDate())); //应收日期
				map.put(head[12]+"_"+i, String.valueOf(info.getOverdueDay())); //到期天数

				listMap.add(map);
			}
		} catch (Exception e) {
			logger.error("组装导出逾期未付款数据错误：{}",e);
		}
		return listMap;
	}
}
